package com.tticar.invmanager.service.impl;

import com.baomidou.mybatisplus.entity.Columns;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.tticar.invmanager.common.Enum.CodeType;
import com.tticar.invmanager.common.Enum.Status;
import com.tticar.invmanager.common.exception.MyServiceException;
import com.tticar.invmanager.common.shiro.MySecurityUtils;
import com.tticar.invmanager.entity.WPosition;
import com.tticar.invmanager.entity.WPositionMateriel;
import com.tticar.invmanager.entity.WWearhouse;
import com.tticar.invmanager.entity.vo.MyPage;
import com.tticar.invmanager.mapper.WPositionMapper;
import com.tticar.invmanager.service.ICodeCounterService;
import com.tticar.invmanager.service.IWPositionMaterielService;
import com.tticar.invmanager.service.IWPositionService;
import com.tticar.invmanager.service.IWWearhouseService;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 库位表 服务实现类
 * </p>
 *
 * @author joeyYan
 * @since 2018-07-31
 */
@Service
@Transactional
public class WPositionServiceImpl extends ServiceImpl<WPositionMapper, WPosition> implements IWPositionService {

    @Autowired
    private ICodeCounterService codeCounterService;
    @Autowired
    private IWPositionMaterielService positionMaterielService;
    @Autowired
    private IWWearhouseService wearhouseService;
    @Override
    public Page selectPage(WPosition wPosition, MyPage<WPosition> page) {
        Wrapper wrapper = new EntityWrapper();
        wrapper.orderBy("ctime", false);
        wrapper.eq(wPosition.getWearhouseIdForSearch() != null, WPosition.WEARHOUSE_ID, wPosition.getWearhouseIdForSearch());
        wrapper.ne(Status.STATUS.getDesc(), Status.DELETE.getCode());
        wrapper.like(Strings.isNotEmpty(wPosition.getName()), WPosition.NAME, wPosition.getName());
        Columns columns = Columns.create().column("*");
        columns.column("(select name from w_wearhouse  where id = w_position.wearhouse_id)", "wname");
//        columns.column("(select name from m_materiel WHERE m_materiel.id = (select materiel_id from w_position_materiel WHERE position_id = w_position.id))", "bindGoods");
        wrapper.setSqlSelect(columns);
        return this.selectMapsPage(page, wrapper);
    }

    @Override
    public Page selectPageByWearhouseId(WPosition wPosition, MyPage<WPosition> page, Long wearhouseId) {
        Wrapper wrapper = new EntityWrapper();
        wrapper.ne(Status.STATUS.getDesc(), Status.DELETE.getCode());
        //wrapper.like(Strings.isNotEmpty(wPosition.getName()), WPosition.NAME, wPosition.getName());
        wrapper.eq(wearhouseId != null, WPosition.WEARHOUSE_ID, wearhouseId);
        Columns columns = Columns.create().column("*");
        columns.column("(select name from w_wearhouse  where id = w_position.wearhouse_id)", "wname");
        wrapper.setSqlSelect(columns);
        return this.selectMapsPage(page, wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(List<Long> ids) {
        List list = new ArrayList();
        for (Long id : ids) {
//            Wrapper wrapper = new EntityWrapper<>();
//            wrapper.eq("position_id", id);
//            wrapper.eq("status", 0);
//            List<WPositionMateriel> wPositionMateriels = positionMaterielService.selectList(wrapper);
//            if (wPositionMateriels != null && wPositionMateriels.size() > 0) {
//                throw new MyServiceException("此库位已经绑定商品，禁止删除");
//            }
            WPosition wPosition = new WPosition();
            wPosition.setId(id);
            //删除为-1，区分删除和禁用
            wPosition.setStatus(-1);
            list.add(wPosition);
        }
        this.updateBatchById(list);
    }

    @Override
    public List<Map> getForTree(Long skuId, Long materielId) {
        Map<String, Object> map = new HashMap<>();
        map.put("skuId", skuId);
        map.put("materielId", materielId);
        map.put("tenantId", MySecurityUtils.currentUser().getTenantId());
        return this.baseMapper.getForTree(map);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void edit(WPosition wPosition) {
        Wrapper wrapper = new EntityWrapper<>();
        wrapper.ne("status", -1);
        wrapper.eq(WPosition.WEARHOUSE_ID, wPosition.getWearhouseId());
        List<WPosition> wPositions = selectList(wrapper);
        if (wPosition.getId() == null) {
            if (wPositions !=null && wPositions.size() > 0) {
                for (WPosition position : wPositions) {
                    if (position.getName().equals(wPosition.getName())) {
                        throw new MyServiceException("此仓库下，已有此库位，请重新命名");
                    }
                }
            }
            Wrapper wrapperWarehouse = new EntityWrapper<>();
            wrapperWarehouse.eq("id", wPosition.getWearhouseId());
            wrapperWarehouse.ne("status", -1);
            List<WWearhouse> wWearhouses = wearhouseService.selectList(wrapperWarehouse);
//            String warehouseCode = "";
//            if (wWearhouses != null && wWearhouses.size() == 1) {
//                warehouseCode = wWearhouses.get(0).getCode().substring(2,4);
//            }
            String code = codeCounterService.getCode(CodeType.KW, wWearhouses.get(0).getId().toString(), 5);
            wPosition.setCode(code);
        }else {
            if (wPositions !=null && wPositions.size() > 0) {
                for (WPosition position : wPositions) {
                    if (position.getName().equals(wPosition.getName()) && !position.getId().equals(wPosition.getId())) {
                        throw new MyServiceException("此仓库下，已有此库位，请重新命名");
                    }
                }
            }
        }

        if (wPosition.getStatus() != 0) {
            //查询该库位是否绑定了商品，如果绑定了商品是不让禁用的
            boolean bindGoods = isBindGoods(wPosition.getId());
            if (bindGoods) {
                throw new MyServiceException("已绑定商品的库位,不能禁用");
            }
        }

        this.insertOrUpdate(wPosition);
    }

    public boolean isBindGoods(Long positionId) {
        String bindGoods = this.baseMapper.isBindGoods(positionId);
        if (StringUtils.isNotBlank(bindGoods)) {
            return true;
        }
        return false;
    }

    @Override
    public List<Map> getForTreeBind(Long materielId) {
        Map<String, Object> map = new HashMap<>();
        map.put("materielId", materielId);
        map.put("tenantId", MySecurityUtils.currentUser().getTenantId());
        return this.baseMapper.getForTreeBind(map);
    }

    @Override
    public List<Long> selectPositionIdsByWearhouseId(Long wearhouseId) {
        return this.baseMapper.selectPositionIdsByWearhouseId(wearhouseId);
    }
}
